#!/usr/bin/python
"""
Author:			Jimmy Saw
Date modified:	08-29-2011

Description:    This script parses gene names from KEGG website given a list of
                KO numbers.

Usage:          dissertation_ECfromKEGG.py <ko.list file>

Example:        dissertation_ECfromKEGG.py ko.list

Note:           ko.list contains locus tag and KO numbers separated by tabs. 

Example:
GLBK_0001	K02313
GLBK_0002	K06980
GLBK_0003	K03980
GLBK_0004
GLBK_0005
GLBK_0006
GLBK_0007
GLBK_0008
GLBK_0009	K03676
GLBK_0010	K01920
"""

import sys
import re
from SOAPpy import WSDL

wsdl = 'http://soap.genome.jp/KEGG.wsdl'
serv = WSDL.Proxy(wsdl)

klistfile = sys.argv[1]

klf = open(klistfile, "rU")
kl = klf.readlines()

pattern = re.compile('.*DEFINITION  .*\[EC:(\d+\.\d+\.\d+\.\d+)\].*')

for line in kl:
    l = line.split('\t')
    if len(l) > 1:
        locustag = l[0]
        ko = l[1].strip()
        q = "orthology:" + ko
        f = serv.bget(q)

        if pattern.search(f):
            m = pattern.search(f)
            print locustag + "\t" + ko + "\t" + m.group(1)
        else:
            print locustag + "\t" + ko + "\t" + "-"
    else:
        print l[0].strip() + "\t" + "-" + "\t" + "-"

klf.close()
